<template>
  <div class="login-bg">
    <div class="login">
      <div class="message">管理登录</div>
      <div class="shadow"></div>
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input placeholder="请输入账号" prefix-icon="fa fa-user-o" v-model="form.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input placeholder="请输入密码" prefix-icon="fa fa-lock" show-password v-model="form.pwd">
          </el-input>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button type="primary" @click="submit('form')">登录</el-button>
          <el-button @click="reset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { login } from '@/network/api.js'
export default {
  name: 'login',
  data () {
    return {
      form: {
        account: '',
        pwd: '',
        type: 1 // 后台登录
      },
      rules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    if (this.$storage.get('token')) {
      this.$router.push('/home')
    }
  },
  methods: {
    // 提交表单
    submit (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const rtn = await login(this.form)
            this.$storage.set('token', rtn.data.token, rtn.data.expires_time)
            this.$storage.set('info', rtn.data.roleinfo, rtn.data.expires_time)
            this.$router.push('/home')
          } catch (e) {
            this.$message.error(e.message)
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    reset (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
</style>
